<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="20">
          <a-col :md="6" :sm="24">
            <a-form-item label="证书名称">
              <a-input v-model="queryParam.certName" placeholder="证书名称"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="证书编号">
              <a-input v-model="queryParam.certId" placeholder="证书编号"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="证书类型">
              <a-select v-model="queryParam.certType" placeholder="请选择">
                <a-select-option
                  v-for="certType in certTypeList"
                  :key="certType.itemVal"
                  :value="certType.itemVal">
                  {{ certType.itemDesc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="颁发单位">
              <a-input v-model="queryParam.certUnit" placeholder="颁发单位"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="颁发日期">
              <a-range-picker mode="year" v-model="queryParam.issueDate" format="YYYY" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="有效期">
              <a-range-picker v-model="queryParam.rangeTime" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
              <a-button style="margin-left: 8px" :loading="importLoading" v-action:import @click="excelImport()">导入</a-button>
              <input
                ref="importInput"
                type="file"
                id="importFile"
                accept=".xls,.xlsx"
                @change="importFile()"
                hidden />
              <a-button style="margin-left: 8px" v-action:export @click="excelExport()">导出</a-button>
              <a-button style="margin-left: 8px" type="primary" v-action:query @click="queryTable()">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchQueryParamBtn()">重置</a-button>
              <a-button type="danger" style="margin-left: 8px" v-action:add @click="newContract()">新增</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      showPagination="auto"
    >
      <span slot="rangeTime" slot-scope="text, record">
        {{ record.beginDate | dateFilter }} - {{ record.endDate | dateFilter }}
      </span>

      <span slot="action" slot-scope="text, record">
        <template>
          <a v-action:get @click="showDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:;" v-action:edit @click="handleEdit(record)">编辑</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" v-action:upload @click="attachmentBtn(record)">附件</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" v-action:delete @click="delCertificate(record)">删除</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </span>
    </s-table>
    <a-modal
      :title="modal.title"
      style="top: 20px;"
      :width="800"
      v-model="modal.visible"
      :maskClosable="false"
    >
      <template slot="footer">
        <a-button v-show="modal.editType === 2 || modal.editType === 1" @click="showAttachmentBtn(modal.rowData)">附件</a-button>
        <a-button v-show="modal.editType !== 2" key="back" @click="handleCancel">
          取消
        </a-button>
        <a-button key="submit" type="primary" :loading="modal.loading" @click="handleOk">
          {{ modal.editType === 2 ? '返回' : '保存' }}
        </a-button>
      </template>
      <a-form class="permission-form" :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          style="display: none"
        >
          <a-input
            v-decorator="['id']"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="证书名称"
        >
          <a-input
            :disabled="this.modal.editType === 2"
            placeholder="证书名称"
            v-decorator="[
              'certName',
              {rules: [{ required: true, message: '请填写证书名称' },
                       { max: 100, message: '证书名称不能超过100字符' }]}]"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="证书编号"
        >
          <a-input
            :disabled="this.modal.editType === 2"
            placeholder="证书编号"
            v-decorator="[
              'certId',
              {rules: [{ max: 200, message: '证书编号不能超过200字符' }]}]"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="证书类型"
        >
          <a-select
            :disabled="this.modal.editType === 2"
            v-decorator="[
              'certType',
              {rules: [{ required: true, message: '请填写部门类型' }]}]"
            placeholder="请选择证书类型">
            <a-select-option
              v-for="cert in certTypeList"
              :key="cert.itemVal"
              :value="cert.itemVal">{{ cert.itemDesc }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="颁发单位"
        >
          <a-input
            :disabled="this.modal.editType === 2"
            placeholder="颁发单位"
            v-decorator="[
              'certUnit',
              {rules: [{ required: true, message: '请输入颁发单位' },
                       { max: 200, message: '颁奖单位不能超过200字符' }]}]"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="颁发日期"
        >
          <a-date-picker
            :disabled="this.modal.editType === 2"
            v-decorator="[
              'issueDate',
              {rules: [{ required: true, message: '请输入颁发日期' }]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="证书有效期"
        >
          <a-range-picker
            :disabled="this.modal.editType === 2"
            v-decorator="[
              'rangeTime']" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="备注"
        >
          <a-textarea
            :disabled="this.modal.editType === 2"
            v-decorator="[
              'note']"
            :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
    <AttachmentModal ref="attachmentModal" :uploadDisabled="modal.uploadDisabled" :attachmentType="'2'"/>
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import AttachmentModal from './modules/AttachmentModal'
import * as api from '../../api/dataManage'
import * as codeApi from '../../api/common'
import pick from 'lodash.pick'
import moment from 'moment'

export default {
  name: 'Certificate',
  components: {
    STable,
    Ellipsis,
    AttachmentModal
  },
  data () {
    return {
      modal: {
        title: '',
        visible: false,
        loading: false,
        editType: 0, // 0 新增状态， 1 编辑状态, 2 详情状态
        rowData: {},
        uploadDisabled: false
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: this.$form.createForm(this),
      // 证书类型
      certTypeList: [],
      // 查询参数
      queryParam: {},
      // 导入文件loading
      importLoading: false,
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          width: '50px',
          key: 'rowIndex',
          customRender: (t, r, index) => {
            return ((this.paginationInfo.pageNum - 1) * this.paginationInfo.pageSize + index + 1)
          }
        },
        {
          title: '证书名称',
          dataIndex: 'certName'
        },
        {
          title: '证书编号',
          dataIndex: 'certId',
          width: '100px'
        },
        {
          title: '证书类型',
          dataIndex: 'certType',
          customRender: (text, row, index) => {
            const certTypeName = this.certTypeList.filter(item => item.itemVal === text)
              ? this.certTypeList.filter(item => item.itemVal === text)[0].itemDesc : text
            return <span>{certTypeName}</span>
          },
          width: '120px'
        },
        {
          title: '颁发单位',
          width: '100px',
          dataIndex: 'certUnit'
        },
        {
          title: '颁发日期',
          dataIndex: 'issueDate',
          width: '100px'
        },
        {
          title: '有效期',
          // dataIndex: 'rangeTime',
          width: '100px',
          scopedSlots: { customRender: 'rangeTime' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      paginationInfo: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.paginationInfo = parameter
        return api.GetCertificateList(Object.assign(parameter, this.queryParam))
          .then(res => {
            console.log('Certificate', res.result)
            return res.result
          })
      },
      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: false, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  filters: {
    dateFilter (date) {
      if (date) {
        return moment(date).format('YYYYMMDD')
      } else {
        return ''
      }
    }
  },
  beforeCreate () {
    codeApi.LasCodeItem({ itemTypeId: 103 }).then(res => {
      this.certTypeList = res.result
    })
  },
  created () {
    this.tableOption()
  },
  methods: {
    newContract () {
      this.modal.title = '新增证书'
      this.form.resetFields()
      this.modal.loading = false
      this.modal.editType = 0
      this.modal.visible = true
      this.modal.rowData = {}
    },
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: false, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    handleEdit (record) {
      this.modal.title = '修改证书'
      this.modal.loading = false
      this.modal.editType = 1
      this.modal.visible = true
      this.modal.rowData = record
      this.modal.uploadDisabled = false
      console.log('record', record)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['id', 'certId', 'certType', 'certName', 'certUnit', 'note']))
        if (record.beginDate === null && record.endDate === null) {
          this.form.setFieldsValue({
            'rangeTime': null,
            'issueDate': moment(record.issueDate)
          })
        } else {
          this.form.setFieldsValue({
            'rangeTime': [moment(record.beginDate), moment(record.endDate)],
            'issueDate': moment(record.issueDate)
          })
        }
      })
    },
    handleOk (e) {
      e.preventDefault()
      if (this.modal.editType === 2) {
        this.modal.visible = false
        return
      }
      this.modal.loading = true
      this.form.validateFields((err, values) => {
        if (err == null) {
          setTimeout(() => {
            console.log(values)
            if (values.rangeTime === undefined || values.rangeTime.length === 0) {
              values.beginDate = ''
              values.endDate = ''
            } else {
              values.beginDate = values.rangeTime[0].format('YYYYMMDD')
              values.endDate = values.rangeTime[1].format('YYYYMMDD')
            }
            delete values.rangeTime
            values.issueDate = values.issueDate.format('YYYYMMDD')
            console.log(values)
            api.SaveCertificate(values).then(res => {
              console.log(res)
              if (res.code === 200) {
                if (res.msg.indexOf('成功') >= 0) {
                  this.$message.success('保存成功！')
                  this.$refs.table.refresh(true)
                  this.modal.loading = false
                  this.modal.visible = false
                } else {
                  this.$message.error('保存失败！' + res.msg)
                  this.modal.loading = false
                }
              } else {
                this.$message.error('服务出错' + res.msg)
                this.modal.loading = false
              }
            }).catch(e => {
              this.$message.error('保存失败！')
              this.modal.loading = false
              console.error(e)
            })
          }, 2000)
        } else {
          this.$message.error('存在非法输入！')
          setTimeout(() => {
            this.modal.loading = false
            this.$nextTick(() => { this.modal.loading = false })
          }, 500)
        }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    certTypeName (certType) {
      return this.certTypeList.filter(item => item.itemVal === certType)
        ? this.certTypeList.filter(item => item.itemVal === certType)[0].itemDesc : certType
    },
    delCertificate (record) {
      const _this = this
      this.$confirm({
        title: '确定删除该证书么',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          api.DelCertificate({ id: record.id }).then(res => {
            if (res.code === 200) {
              if (res.msg.indexOf('成功') >= 0) {
                _this.$message.success('删除成功！')
                _this.$refs.table.refresh(true)
              } else {
                _this.$message.error('删除失败！' + res.msg)
              }
            } else {
              _this.$message.error('服务出错' + res.msg)
            }
          })
        },
        onCancel () {
        }
      })
    },
    excelExport () {
      const ids = this.selectedRows.map(item => {
        return item.id
      })
      console.log('ids', ids)
      if (ids.length === 0) {
        this.$message.warning('请勾选需要导出的数据')
        return
      }
      api.ExportCertificate({ ids: ids }).then((result) => {
        console.log(result)
        const _this = this
        const r = new FileReader()
        r.readAsText(result)
        r.onload = function () {
          try {
            const res = JSON.parse(this.result)
            console.log(res)
            if (res.code && res.code === 500) {
              _this.$message.error('导出失败，' + res.msg)
            }
          } catch (err) {
            const link = document.createElement('a')
            link.href = window.URL.createObjectURL(new Blob([result]))
            link.target = '_blank'
            link.download = '证书列表.xls'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        }
      }).catch((err) => {
        console.log(err)
        this.$message.error('导出失败')
        this.$message.error(err)
      })
    },
    excelImport () {
      this.$refs.importInput.click()
    },
    importFile () {
      this.importLoading = true
      const file = document.querySelector('#importFile').files[0]
      if (file === null) {
        this.importLoading = false
        return
      }
      const fileName = file.name
      const fileSize = file.size / (1024 * 1024)
      const idx = fileName.lastIndexOf('.')
      if (idx !== -1) {
        let ext = fileName.substr(idx + 1).toUpperCase()
        ext = ext.toLowerCase()
        if (ext !== 'xls' && ext !== 'xlsx') {
          this.$message.error('导入文件格式不对, 只能导入xls,xlsx格式文件！')
          this.importLoading = false
          return
        }
      } else {
        this.$message.error('导入文件格式不对, 只能导入xls,xlsx格式文件！')
        this.importLoading = false
        return
      }
      if (fileSize > 10) {
        this.$message.error('导入文件大小不能超过10MB')
        this.importLoading = false
        return
      }
      const formData = new FormData()
      formData.append('file', file)
      console.log(file)
      this.$refs.importInput.value = null
      api.ImportCertificate(formData).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success('导入成功')
          this.importLoading = false
          this.$refs.table.refresh(true)
        } else {
          this.$message.error('导入失败！')
          this.$warning({
            title: '导入失败',
            content: (h) => {
              const data = res.msg
              return h('a-textarea', {
                attrs: {
                  readonly: true
                },
                props: {
                  defaultValue: data,
                  autoSize: { minRows: 5, maxRows: 10 }
                }
              })
            }
          })
          this.importLoading = false
        }
      }).catch(e => {
        console.error(e)
        this.$message.error('导入失败！')
        this.importLoading = false
      })
    },
    showDetail (record) {
      this.modal.title = '证书详情'
      this.modal.loading = false
      this.modal.editType = 2
      this.modal.visible = true
      this.modal.rowData = record
      this.modal.uploadDisabled = true
      console.log('record', record)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['id', 'certId', 'certType', 'certName',
          'certUnit', 'note']))
        if (record.beginDate === null && record.endDate === null) {
          this.form.setFieldsValue({
            'rangeTime': null,
            'issueDate': moment(record.issueDate)
          })
        } else {
          this.form.setFieldsValue({
            'rangeTime': [moment(record.beginDate), moment(record.endDate)],
            'issueDate': moment(record.issueDate)
          })
        }
      })
    },
    queryTable () {
      delete this.queryParam.beginDate
      delete this.queryParam.endDate
      delete this.queryParam.issueDateStart
      delete this.queryParam.issueDateEnd
      if (this.queryParam.rangeTime && this.queryParam.rangeTime.length !== 0) {
        this.queryParam.beginDate = this.queryParam.rangeTime[0].format('YYYYMMDD')
        this.queryParam.endDate = this.queryParam.rangeTime[1].format('YYYYMMDD')
      }
      if (this.queryParam.issueDate && this.queryParam.issueDate.length !== 0) {
        this.queryParam.issueDateStart = this.queryParam.issueDate[0].format('YYYY') + '0101'
        this.queryParam.issueDateEnd = this.queryParam.issueDate[1].format('YYYY') + '1231'
      }
      this.$refs.table.refresh(true)
    },
    handleCancel () {
      this.modal.visible = false
    },
    resetSearchQueryParamBtn () {
      this.queryParam = {}
      this.queryTable()
    },
    attachmentBtn (record) {
      this.modal.uploadDisabled = false
      this.showAttachmentBtn(record)
    },
    showAttachmentBtn (record) {
      this.$refs.attachmentModal.clearFileList()
      this.$refs.attachmentModal.show(record)
    }
  }
}
</script>
